/**
 * 校园二手交易平台 - 商品详情页面
 * 完整的商品展示页面，包含商品信息、发布者信息、操作按钮和相关推荐
 */

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from '@umijs/max';
import {
  Row,
  Col,
  Card,
  Button,
  Space,
  Tag,
  Spin,
  Alert,
  message,
  Divider,
  Rate,
  Image,
  Carousel,
  Avatar,
  Statistic,
  Tooltip,
  Popover,
  Modal
} from 'antd';
import {
  HeartOutlined,
  HeartFilled,
  ShareAltOutlined,
  MessageOutlined,
  PhoneOutlined,
  WechatOutlined,
  EnvironmentOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  ShoppingCartOutlined,
  ExclamationCircleOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import type { Product, ProductCategory } from '../../types/product';
import {
  PRODUCT_CATEGORY_DISPLAY_NAMES,
  PRODUCT_CONDITION_DISPLAY_NAMES,
  PRODUCT_STATUS_DISPLAY_NAMES,
  TRANSACTION_METHOD_DISPLAY_NAMES,
  isProductPurchasable
} from '../../types/product';
import { productService } from '../../services/productService';
import ProductCard from '../../components/products/ProductCard';

// 图片轮播组件
const ProductImageCarousel: React.FC<{ images: Product['images'] }> = ({ images }) => {
  if (!images || images.length === 0) {
    return (
      <div className="w-full h-96 bg-gray-100 flex items-center justify-center">
        <div className="text-gray-400 text-lg">暂无图片</div>
      </div>
    );
  }

  return (
    <Carousel autoplay dots={{ className: 'custom-dots' }}>
      {images.map((image) => (
        <div key={image.id} className="h-96">
          <Image
            src={image.url}
            alt={image.description || '商品图片'}
            className="w-full h-full object-cover"
            placeholder={
              <div className="flex items-center justify-center bg-gray-100 h-full">
                <Spin size="large" />
              </div>
            }
          />
        </div>
      ))}
    </Carousel>
  );
};

// 发布者信息组件
const PublisherInfo: React.FC<{ publisher: Product['publisher'] }> = ({ publisher }) => {
  const [contactModalVisible, setContactModalVisible] = useState(false);

  const handleContact = () => {
    setContactModalVisible(true);
  };

  return (
    <>
      <Card title="发布者信息" size="small" className="h-full">
        <div className="flex items-center space-x-4 mb-4">
          <Avatar 
            size={64} 
            src={publisher.avatar} 
            icon={<UserOutlined />}
            className="border-2 border-blue-100"
          />
          <div className="flex-1">
            <div className="flex items-center space-x-2 mb-1">
              <span className="text-lg font-semibold">{publisher.username}</span>
              {publisher.isStudentVerified && (
                <Tag color="green" icon={<UserOutlined />}>
                  学生认证
                </Tag>
              )}
            </div>
            <div className="text-gray-600 text-sm">
              <EnvironmentOutlined className="mr-1" />
              {publisher.school}
            </div>
          </div>
        </div>
        
        <div className="space-y-3">
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">信誉评分</span>
            <Rate disabled defaultValue={4.5} allowHalf className="text-sm" />
          </div>
          
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">发布商品</span>
            <span className="font-medium">23件</span>
          </div>
          
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">成交记录</span>
            <span className="font-medium">18笔</span>
          </div>
        </div>
        
        <Divider className="my-4" />
        
        <Space direction="vertical" className="w-full">
          <Button 
            type="primary" 
            icon={<MessageOutlined />} 
            block
            onClick={handleContact}
          >
            联系发布者
          </Button>
          
          {publisher.contactInfo && (
            <Button 
              icon={<PhoneOutlined />} 
              block
              onClick={() => {
                if (publisher.contactInfo?.phone) {
                  message.info(`联系电话：${publisher.contactInfo.phone}`);
                }
              }}
            >
              查看电话
            </Button>
          )}
        </Space>
      </Card>

      <Modal
        title="联系发布者"
        open={contactModalVisible}
        onCancel={() => setContactModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setContactModalVisible(false)}>
            取消
          </Button>,
          <Button key="copy" type="primary">
            复制联系方式
          </Button>
        ]}
      >
        <div className="space-y-4">
          <div className="text-center">
            <Avatar size={80} src={publisher.avatar} icon={<UserOutlined />} />
            <div className="mt-2">
              <div className="text-lg font-semibold">{publisher.username}</div>
              <div className="text-gray-600">{publisher.school}</div>
            </div>
          </div>
          
          <div className="space-y-2">
            {publisher.contactInfo?.phone && (
              <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                <span>电话：</span>
                <span className="font-mono">{publisher.contactInfo.phone}</span>
              </div>
            )}
            
            {publisher.contactInfo?.wechat && (
              <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                <span>微信：</span>
                <span className="font-mono">{publisher.contactInfo.wechat}</span>
              </div>
            )}
            
            {publisher.contactInfo?.qq && (
              <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                <span>QQ：</span>
                <span className="font-mono">{publisher.contactInfo.qq}</span>
              </div>
            )}
          </div>
          
          <Alert 
            message="请通过平台认可的方式联系，谨防诈骗" 
            type="warning" 
            showIcon 
          />
        </div>
      </Modal>
    </>
  );
};

// 操作按钮区域
const ActionButtons: React.FC<{ 
  product: Product; 
  isFavorited: boolean; 
  onFavorite: () => void;
  onPurchase: () => void;
}> = ({ product, isFavorited, onFavorite, onPurchase }) => {
  const isPurchasable = isProductPurchasable(product);

  const handleShare = () => {
    // 分享功能实现
    if (navigator.share) {
      navigator.share({
        title: product.title,
        text: product.description,
        url: window.location.href,
      });
    } else {
      // 复制链接到剪贴板
      navigator.clipboard.writeText(window.location.href);
      message.success('链接已复制到剪贴板');
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex space-x-3">
        <Button 
          type="primary" 
          size="large" 
          icon={<ShoppingCartOutlined />}
          disabled={!isPurchasable}
          onClick={onPurchase}
          className="flex-1"
        >
          {isPurchasable ? '立即购买' : '已售罄'}
        </Button>
        
        <Button 
          type={isFavorited ? 'primary' : 'default'}
          size="large"
          icon={isFavorited ? <HeartFilled /> : <HeartOutlined />}
          onClick={onFavorite}
          className={`${isFavorited ? 'text-red-500 border-red-500' : ''}`}
        >
          {isFavorited ? '已收藏' : '收藏'}
        </Button>
      </div>
      
      <div className="flex space-x-2">
        <Tooltip title="分享商品">
          <Button 
            icon={<ShareAltOutlined />} 
            size="middle"
            onClick={handleShare}
          >
            分享
          </Button>
        </Tooltip>
        
        <Tooltip title="举报商品">
          <Button 
            icon={<ExclamationCircleOutlined />} 
            size="middle"
            danger
          >
            举报
          </Button>
        </Tooltip>
      </div>
    </div>
  );
};

// 商品详情统计信息
const ProductStats: React.FC<{ product: Product }> = ({ product }) => (
  <div className="grid grid-cols-3 gap-4 text-center">
    <Statistic 
      title="浏览量" 
      value={product.viewCount} 
      prefix={<EyeOutlined />}
      valueStyle={{ fontSize: '16px' }}
    />
    <Statistic 
      title="收藏数" 
      value={product.favoriteCount} 
      prefix={<HeartOutlined />}
      valueStyle={{ fontSize: '16px' }}
    />
    <Statistic 
      title="咨询数" 
      value={product.inquiryCount} 
      prefix={<MessageOutlined />}
      valueStyle={{ fontSize: '16px' }}
    />
  </div>
);

// 相关商品推荐
const RelatedProducts: React.FC<{ category: ProductCategory; currentProductId: string }> = ({ 
  category, 
  currentProductId 
}) => {
  const [relatedProducts, setRelatedProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchRelatedProducts = async () => {
      try {
        setLoading(true);
        const response = await productService.getProducts({
          category,
          pageSize: 4,
          onlyActive: true
        });
        
        // 过滤掉当前商品
        const filteredProducts = response.products
          .filter(p => p.id !== currentProductId)
          .slice(0, 3);
        
        setRelatedProducts(filteredProducts);
      } catch (error) {
        console.error('获取相关商品失败:', error);
        message.error('获取相关商品失败');
      } finally {
        setLoading(false);
      }
    };

    fetchRelatedProducts();
  }, [category, currentProductId]);

  if (loading) {
    return <Spin tip="加载相关商品..." />;
  }

  if (relatedProducts.length === 0) {
    return null;
  }

  return (
    <div className="mt-8">
      <Divider orientation="left">
        <span className="text-lg font-semibold">相关推荐</span>
      </Divider>
      
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {relatedProducts.map(product => (
          <ProductCard
            key={product.id}
            product={product}
            size="small"
            showFavorite={true}
            showCart={true}
          />
        ))}
      </div>
    </div>
  );
};

// 主商品详情页面组件
const ProductDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [isFavorited, setIsFavorited] = useState(false);

  // 获取商品详情
  useEffect(() => {
    const fetchProductDetail = async () => {
      if (!id) {
        setError('商品ID不能为空');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const productData = await productService.getProduct(id);
        setProduct(productData);
        setIsFavorited(productData.favoriteCount > 0);
      } catch (err) {
        console.error('获取商品详情失败:', err);
        setError('商品不存在或已下架');
      } finally {
        setLoading(false);
      }
    };

    fetchProductDetail();
  }, [id]);

  // 处理收藏操作
  const handleFavorite = async () => {
    if (!product) return;

    try {
      if (isFavorited) {
        await productService.unfavoriteProduct(product.id);
        setIsFavorited(false);
        message.success('取消收藏成功');
      } else {
        await productService.favoriteProduct(product.id);
        setIsFavorited(true);
        message.success('收藏成功');
      }
      
      // 更新商品数据
      const updatedProduct = await productService.getProduct(product.id);
      setProduct(updatedProduct);
    } catch (error) {
      console.error('收藏操作失败:', error);
      message.error('操作失败，请重试');
    }
  };

  // 处理购买操作
  const handlePurchase = () => {
    if (!product) return;

    if (!isProductPurchasable(product)) {
      message.warning('该商品已售罄或已下架');
      return;
    }

    Modal.confirm({
      title: '确认购买',
      content: `确定要购买「${product.title}」吗？`,
      okText: '确认购买',
      cancelText: '取消',
      onOk: () => {
        message.success('购买成功！请尽快联系发布者完成交易');
        // 这里可以添加购买逻辑
      }
    });
  };

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-96">
        <Spin size="large" tip="加载商品详情..." />
      </div>
    );
  }

  if (error || !product) {
    return (
      <div className="max-w-4xl mx-auto p-6">
        <Alert
          message="商品加载失败"
          description={error || '商品不存在或已下架'}
          type="error"
          showIcon
          action={
            <Button size="small" onClick={handleBack}>
              返回
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div className="product-detail-page">
      {/* 返回按钮 */}
      <div className="mb-4">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          className="text-gray-600 hover:text-blue-600"
        >
          返回
        </Button>
      </div>

      <div className="max-w-6xl mx-auto">
        <Row gutter={[24, 24]}>
          {/* 商品图片区域 */}
          <Col xs={24} lg={12}>
            <Card 
              className="shadow-sm"
              bodyStyle={{ padding: 0 }}
            >
              <ProductImageCarousel images={product.images} />
              
              {/* 商品状态标签 */}
              <div className="p-4 border-t border-gray-100">
                <div className="flex justify-between items-center">
                  <Tag 
                    color={product.status === 'active' ? 'green' : 'red'}
                    className="text-sm"
                  >
                    {PRODUCT_STATUS_DISPLAY_NAMES[product.status]}
                  </Tag>
                  
                  <div className="text-sm text-gray-500">
                    <ClockCircleOutlined className="mr-1" />
                    发布于 {new Date(product.publishedAt).toLocaleDateString()}
                  </div>
                </div>
              </div>
            </Card>
          </Col>

          {/* 商品信息区域 */}
          <Col xs={24} lg={12}>
            <div className="space-y-6">
              {/* 商品基本信息 */}
              <Card title="商品信息" size="small">
                <div className="space-y-4">
                  <div>
                    <h1 className="text-2xl font-bold text-gray-900 mb-2">
                      {product.title}
                    </h1>
                    
                    <div className="flex items-center space-x-2 mb-4">
                      <span className="text-3xl font-bold text-red-600">
                        ¥{product.price}
                      </span>
                      {product.originalPrice && product.originalPrice > product.price && (
                        <span className="text-lg text-gray-500 line-through">
                          ¥{product.originalPrice}
                        </span>
                      )}
                    </div>
                  </div>

                  {/* 商品标签 */}
                  <div className="flex flex-wrap gap-2">
                    <Tag color="blue">
                      {PRODUCT_CATEGORY_DISPLAY_NAMES[product.category]}
                    </Tag>
                    <Tag color="green">
                      {PRODUCT_CONDITION_DISPLAY_NAMES[product.condition]}
                    </Tag>
                    <Tag color="orange">
                      {TRANSACTION_METHOD_DISPLAY_NAMES[product.transactionMethod]}
                    </Tag>
                    {product.isNegotiable && <Tag color="purple">可议价</Tag>}
                    {product.isFreeShipping && <Tag color="cyan">包邮</Tag>}
                    {product.isReturnable && <Tag color="magenta">支持退换</Tag>}
                  </div>

                  {/* 商品统计 */}
                  <ProductStats product={product} />
                </div>
              </Card>

              {/* 操作按钮区域 */}
              <Card size="small">
                <ActionButtons
                  product={product}
                  isFavorited={isFavorited}
                  onFavorite={handleFavorite}
                  onPurchase={handlePurchase}
                />
              </Card>

              {/* 发布者信息 */}
              <PublisherInfo publisher={product.publisher} />
            </div>
          </Col>
        </Row>

        {/* 商品详细描述 */}
        <Row className="mt-6">
          <Col span={24}>
            <Card title="商品描述" size="small">
              <div className="prose max-w-none">
                <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
                  {product.description}
                </p>
              </div>
              
              {/* 商品标签 */}
              {product.tags && product.tags.length > 0 && (
                <div className="mt-4 pt-4 border-t border-gray-100">
                  <div className="flex flex-wrap gap-2">
                    {product.tags.map((tag, index) => (
                      <Tag key={index} color="geekblue">
                        {tag}
                      </Tag>
                    ))}
                  </div>
                </div>
              )}
            </Card>
          </Col>
        </Row>

        {/* 物流和退换货信息 */}
        <Row gutter={[16, 16]} className="mt-6">
          <Col xs={24} md={12}>
            <Card title="物流信息" size="small">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-600">交易方式：</span>
                  <span>{TRANSACTION_METHOD_DISPLAY_NAMES[product.transactionMethod]}</span>
                </div>
                
                <div className="flex justify-between">
                  <span className="text-gray-600">配送方式：</span>
                  <span>{product.isFreeShipping ? '包邮' : '买家承担邮费'}</span>
                </div>
                
                {!product.isFreeShipping && product.shippingFee && (
                  <div className="flex justify-between">
                    <span className="text-gray-600">预估邮费：</span>
                    <span>¥{product.shippingFee}</span>
                  </div>
                )}
                
                <div className="flex justify-between">
                  <span className="text-gray-600">所在位置：</span>
                  <span>{product.location.school} {product.location.campus}</span>
                </div>
              </div>
            </Card>
          </Col>
          
          <Col xs={24} md={12}>
            <Card title="退换货政策" size="small">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-600">是否支持退换：</span>
                  <span>{product.isReturnable ? '支持' : '不支持'}</span>
                </div>
                
                {product.isReturnable && (
                  <div className="text-sm text-gray-600">
                    {product.returnPolicy || '商品存在质量问题支持7天内退换货'}
                  </div>
                )}
                
                <div className="flex justify-between">
                  <span className="text-gray-600">库存数量：</span>
                  <span>{product.stock}件</span>
                </div>
                
                <div className="text-xs text-gray-500">
                  最后更新：{new Date(product.updatedAt).toLocaleString()}
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 相关商品推荐 */}
        <RelatedProducts 
          category={product.category} 
          currentProductId={product.id}
        />
      </div>
    </div>
  );
};

export default ProductDetailPage;